package com.sudworth.repository.db;

import android.content.Context;

import androidx.room.Room;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.commonsware.cwac.saferoom.SafeHelperFactory;

import org.jetbrains.annotations.NotNull;

/**
 * @Author: shalei
 * @Date: 2019-10-21 15:51
 * @Desc:
 **/
public class DBProxy {

    private static final DBProxy instance = new DBProxy();

    public static DBProxy getInstance() {
        return instance;
    }

    private AppDatabase mAppDatabase;

    private DBProxy() {
    }

    public void init(Context context, String dbName) {
        mAppDatabase = Room.databaseBuilder(context, AppDatabase.class, dbName)
//                .addMigrations(MIGRATION_1_2)
                //abcd123 加密和非加密数据库不兼容，需要对原有数据库进行copy重新写入
                .openHelperFactory(new SafeHelperFactory("abcd123".toCharArray()))
                .allowMainThreadQueries() //main线程调用
                .build();

        //重置密码
//        SafeHelperFactory.rekey(mAppDatabase.getOpenHelper().getWritableDatabase(), "fa113213a".toCharArray());
    }

    public AppDatabase getDbHelper() {
        return mAppDatabase;
    }

    private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(@NotNull SupportSQLiteDatabase database) {
            database.execSQL("CREATE TABLE IF NOT EXISTS `region` (`id` INTEGER NOT NULL, `pid` INTEGER NOT NULL, `short_name` TEXT NOT NULL, `name` TEXT NOT NULL, `merger_name` TEXT NOT NULL, `level` INTEGER NOT NULL, `pinyin` TEXT NOT NULL, `phone_code` TEXT NOT NULL, `zip_code` TEXT NOT NULL, `first` TEXT NOT NULL, `lng` TEXT NOT NULL, `lat` TEXT NOT NULL, `short_name_en` TEXT NOT NULL, `areaCode` TEXT NOT NULL, `display` INTEGER NOT NULL, PRIMARY KEY(`id`))");
        }
    };
}
